package com.vframework.system.user.entity;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonView;
import com.vframework.base.entity.BaseEntity;
import com.vframework.common.response.jsonview.GeneralViews;
import com.vframework.system.permission.entity.SysPermission;
import com.vframework.system.role.entity.SysRole;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.experimental.Accessors;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import javax.validation.constraints.NotBlank;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表
 * </p>
 *
 * @author jobob
 * @since 2019-02-22
 */
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("sys_user")
@JsonInclude(JsonInclude.Include.NON_NULL)
@ApiModel("用户表")
public class SysUser extends BaseEntity<SysUser> implements UserDetails {

    private static final long serialVersionUID = 1L;

    // 简单视图，屏蔽密码、角色列表等内容
    public interface UserSimpleView extends GeneralViews.SimpleView {}
    // 详情视图，显示角色列表等内容
    public interface UserDetailView extends UserSimpleView, GeneralViews.DetailView {}
    // 不可见视图，屏蔽权限列表、令牌等后台内容，不使用户感知
    public interface SystemView {}

    /**
     * 主键
     */
    @ApiModelProperty("用户id")
    @TableId(type = IdType.AUTO)
    @Getter(onMethod = @__(@JsonView(UserSimpleView.class)))
    private Integer id;

    /**
     * 用户名
     */
    @ApiModelProperty("用户名")
    @TableField("username")
    @Getter(onMethod = @__(@JsonView(UserSimpleView.class)))
    @NotBlank(message = "用户名不能为空")
    private String username;

    /**
     * 密码
     */
    @ApiModelProperty("密码")
    @TableField("password")
    @Getter(onMethod = @__(@JsonView(UserDetailView.class)))
    @NotBlank(message = "密码不能为空")
    private String password;

    /**
     * 昵称
     */
    @ApiModelProperty("昵称")
    @TableField("nickname")
    @Getter(onMethod = @__(@JsonView(UserSimpleView.class)))
    private String nickname;

    /**
     * 电话
     */
    @ApiModelProperty("电话")
    @TableField("phone")
    @Getter(onMethod = @__(@JsonView(UserSimpleView.class)))
    private String phone;

    /**
     * 头像
     */
    @ApiModelProperty("头像")
    @TableField("head_img_url")
    @Getter(onMethod = @__(@JsonView(UserSimpleView.class)))
    private String headImgUrl;

    /**
     * 机构id
     */
    @ApiModelProperty("机构id")
    @TableField("status")
    @Getter(onMethod = @__(@JsonView(UserSimpleView.class)))
    private Integer orgId;

    /**
     * 状态 0-不可用 1-可用
     */
    @ApiModelProperty("状态 0-不可用 1-可用")
    @TableField("status")
    @Getter(onMethod = @__(@JsonView(UserSimpleView.class)))
    private Integer status;

    /** 角色列表 */
    @ApiModelProperty("角色列表")
    @TableField(exist = false)
    @Getter(onMethod = @__(@JsonView(UserDetailView.class)))
    private List<SysRole> roleList;

    @ApiModelProperty("令牌")
    @TableField(exist = false)
    @Getter(onMethod = @__(@JsonView(SystemView.class)))
    private String token;

    /** 登陆时间戳（毫秒） */
    @ApiModelProperty("登录时间")
    @TableField(exist = false)
    @Getter(onMethod = @__(@JsonView(SystemView.class)))
    private Long loginTime;

    /** 过期时间戳 */
    @ApiModelProperty("过期时间")
    @TableField(exist = false)
    @Getter(onMethod = @__(@JsonView(SystemView.class)))
    private Long expireTime;

    /** 权限列表 */
    @ApiModelProperty("权限列表")
    @TableField(exist = false)
    @Getter(onMethod = @__(@JsonView(SystemView.class)))
    private List<SysPermission> permissions;

    /** 角色列表 */
//    @TableField(exist = false)
//    private List<SysPermission> permissions;


    @Override
    protected Serializable pkVal() {
        return null;
    }

    public enum UserStatusEnum {
        //作废
        DISABLED(0, "已作废"),
        //有效
        VALID(1, "有效"),
        //锁定
        LOCKED(2, "锁定");

        @Getter
        private Integer code;

        @Getter
        private String value;

        UserStatusEnum(Integer code, String value) {
            this.code = code;
            this.value = value;
        }

        public static String getValue(Integer code) {
            if (code != null) {
                UserStatusEnum[] statusEnums = values();
                for (UserStatusEnum statusEnum: statusEnums) {
                    if (statusEnum.getCode().equals(code)) {
                        return statusEnum.getValue();
                    }
                }
            }
            return null;
        }
    }

    /*@JsonView(UserSimpleView.class)
    public String getStatusText() {
        return UserStatusEnum.getValue(getStatus());
    }*/

    @Override
    @JsonIgnore
    //@JsonIgnore json忽略
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return permissions.parallelStream().filter(p -> StrUtil.isNotBlank(p.getPermission()))
                .map(p -> new SimpleGrantedAuthority(p.getPermission())).collect(Collectors.toSet());
    }

    // 账户是否未过期
    @JsonIgnore
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    // 账户是否未锁定
    @JsonIgnore
    @Override
    public boolean isAccountNonLocked() {
        return getStatus() != UserStatusEnum.LOCKED.getCode();
    }

    // 密码是否未过期
    @JsonIgnore
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    // 账户是否激活
    @JsonIgnore
    @Override
    public boolean isEnabled() {
        return true;
    }
}
